<?php

//------------------------
// 商品品牌控制器
//-------------------------
namespace app\admin\controller;

use app\common\controller\AdminBase;
use app\common\model\GoodsBrand as GoodsBrandModel;
use app\common\model\GoodsCateBrandView as GoodsCateBrandViewModel;
use think\Config;
use think\Db;

class GoodsBrand extends AdminBase
{
    protected $GoodsBrandModel;
    protected $GoodsCateBrandViewModel;

    protected function _initialize()
    {
        parent::_initialize();
        $this->GoodsBrandModel               = new GoodsBrandModel();
        $this->GoodsCateBrandViewModel       = new GoodsCateBrandViewModel();
    }


    // 品牌列表
    public function index(){
        $brand_name    = $this->request->param('brand_name','','trim');

        $where = array();

        if ($brand_name) {
             $where['brand_name'] = array('like','%'.$brand_name.'%');
        }


        $info = $this->GoodsBrandModel->where($where)->order('seq')->
          paginate(10,false,['query' => [
            'brand_name'  =>$brand_name
            ] ]);

        $this->assign('brand_name',$brand_name);
        $this->assign('info',$info);

        return $this->fetch('index');
    }


    // 添加页面
    function add(){
        return $this->fetch('add');
    }

    /**
     * @desc 添加操作
     */
    public function addProc() {
        $data            = $this->request->param();

        $validate_result = $this->validate($data, 'GoodsBrand');

        if ($validate_result !== true) {
                $this->error($validate_result);
        }

        $addData = array(
            'brand_name'        => $data['brand_name'],
            'seq'               => $data['seq']
        );

        $res = $this->GoodsBrandModel->save($addData);

        if ($res === false) {
            $this->error($this->GoodsBrandModel->getError());
        } else {
            $this->success('添加成功');
        }
    }

    /**
     * @desc AJAX上传图片
     */
    public function uploadImage() {
        $id = $this->request->param('id',0,'intval');
        $path = $this->request->param('path','other','trim');

        if (!$id) {
            $this->error('缺少要上传图片的品牌id');
        }

        // 获取表单上传文件 
        $file = request()->file('image');

        $info = $file->validate(Config::get('image_validate'))->move(Config::get('image_path') . $path);


        // 删除替换前的图片
        $image = Db('GoodsBrand')->where('id',$id)->field('brand_logo')->find();

        // 删除文件
        delete_file('goods_brand',$image['brand_logo']);

        if($info){
            // 返回图片地址
            $return_url = show_image($path, $info->getSaveName());

            // 保存图名字到数据库
            $data['brand_logo'] = $info->getSaveName();
            $data['id'] = $id;

            $res =  $this->GoodsBrandModel->allowField(true)->save($data,$data['id']);

            $return = array('msg' => '上传成功','url'=>$return_url, 'code' => 1);
        }else{
            // 上传失败获取错误信息
            $return = array('msg' => $file->getError(), 'code' => 0);
        }
        echo json_encode($return);
    }

    // 编辑页面
    function edit(){
        $id = $this->request->param('id',0,'intval');

        $data = $this->GoodsBrandModel->get($id);

        $this->assign('data',$data);
        return $this->fetch('edit');
    }

    // 编辑操作
    function editProc(){
        $data  = $this->request->param('');

        $validate_result = $this->validate($data, 'GoodsBrand');

        if ($validate_result !== true) {
                $this->error($validate_result);
        }

        $res = $this->GoodsBrandModel->allowField(true)->save($data,$data['id']);

        if ($res === false) {
            $this->error($this->GoodsBrandModel->getError());
        } else {
            $this->success('保存成功');
        }
    }



    // 删除操作
    public function delete(){
        $id = $this->request->param('id',0,'intval');

        $where['id'] = array('eq',$id);

        // 删除品牌图片
        $image = Db('GoodsBrand')->where('id',$id)->field('brand_logo')->find();

        // 删除文件
        delete_file('goods_brand',$image['brand_logo']);

        $res = $this->GoodsBrandModel->where($where)->delete();

        if ($res == false) {
            $this->error($this->GoodsBrandModel->getError());
        } else{
            // 删除成功后，才删除中间表的数据
            // $this->AuthGroupAccessModel->where('uid',$id)->delete();
            $this->success('删除成功');
        }
    }




    // 批量删除>>调用
    private function _batchDelete($id){
        $where['id'] = array('eq',$id);

        //  先找出图片路径
        $image = Db('GoodsBrand')->where('id',$id)->field('brand_logo')->find();

        $res = $this->GoodsBrandModel->where($where)->delete();

        if ($res == false) {
           return false;
        } else {
            // 删除文件
            delete_file('goods_brand',$image['brand_logo']);

            return true;
        }

    }


    // 批量处理
    public function batchProc(){
        $data = $this->request->param();

        $ids = implode(',',$data['ids']);
        $map['id']  = ['in',$ids];
        $type = $data['type'];

        switch ($type) {
            case 'delete':
                $successData = array();
                $failData = array();
                for ($i=0; $i < count($data['ids']); $i++) { 
                    $result = $this->_batchDelete($data['ids'][$i]);
                    if ($result) {
                        array_push($successData, $data['ids'][$i]);
                    } else {
                        array_push($failData, $data['ids'][$i]);
                    }
                }
                $success = implode(',',$successData);
                $fail   = implode(',',$failData);
                $this->success('删除成功id为：'.$success.'，删除失败id为：'.$fail);
                break;
            default:
                $this->error('非法操作');
                break;
        }

        if ($res === false) {
            $this->error($this->GoodsBrandModel->getError());
        } else {
            $this->success('批量'.$act.'成功');
        }

    }

    // ajax 方式获取分类下面品牌
    public function ajaxGetBrand(){
        $id = $this->request->param('id',0,'intval');

        $info = $this->GoodsCateBrandViewModel->where('platform_goods_cate.id',$id) ->select()->toArray();

        $this->success($info);
    }




}